//
//  ICChatMessageBaseCell.m
//  ICome
//
//  Created by ENN on 16/3/12.
//  Copyright © 2016年 iCom. All rights reserved.
//

#import "ICChatMessageBaseCell.h"
#import "ICMessageModel.h"
#import "ICMessage.h"
#import "ICMessageTopView.h"
#import "ICMessageDatabase.h"
#import "ICHeaderFile.h"
@interface ICChatMessageBaseCell ()

@property (nonatomic, strong) ICMessageTopView *topView;

@end

@implementation ICChatMessageBaseCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self setupUI];
        self.backgroundColor = [UIColor clearColor];
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        
        UILongPressGestureRecognizer *longRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressRecognizer:)];
        longRecognizer.minimumPressDuration = 0.3;
        [self.contentView addGestureRecognizer:longRecognizer];
    }
    return self;
}

#pragma mark - UI

- (void)setupUI {
    [self.contentView addSubview:self.bubbleView];
    [self.contentView addSubview:self.topView];
    [self.contentView addSubview:self.headImageView];
    [self.contentView addSubview:self.activityView];
    [self.contentView addSubview:self.retryButton];
}

#pragma mark - Getter and Setter

- (ICHeadImageView *)headImageView {
    if (_headImageView == nil) {
        _headImageView = [[ICHeadImageView alloc] init];
        [_headImageView setColor:IColor(219, 220, 220) bording:0.0];
        UITapGestureRecognizer *singleFingerOne = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headClicked:)];
        singleFingerOne.numberOfTapsRequired = 1;
        [_headImageView addGestureRecognizer:singleFingerOne];
        
        
        UILongPressGestureRecognizer *longRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longRecognizerClicked:)];
        //                                                        initWithActionBlock:^(id  _Nonnull sender) {
        //            NSLog(@" -- ");
        //            if (longRecognizer.state == UIGestureRecognizerStateBegan) {
        //                if(_modelFrame.model.message.from && _modelFrame.model.message.senderName){
        //                    //\u2005
        //                    NSString * name = [NSString stringWithFormat:@"%@\u2005",_modelFrame.model.message.senderName];
        //
        //                    NSDictionary * dict = @{_modelFrame.model.message.from:name};
        //                    [self routerEventWithName:GXRouterEventsingleFingerTwo userInfo:dict];
        //                }
        //
        //            }else {
        //            }
        //        }];
        longRecognizer.minimumPressDuration = 0.3;
        [_headImageView addGestureRecognizer:longRecognizer];
    }
    return _headImageView;
}

- (UIImageView *)bubbleView {
    if (!_bubbleView) {
        _bubbleView = [[UIImageView alloc] init];
    }
    return _bubbleView;
}

- (UIActivityIndicatorView *)activityView {
    if (_activityView == nil) {
        _activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    }
    return _activityView;
}

- (UIButton *)retryButton {
    if (_retryButton == nil) {
        _retryButton = [[UIButton alloc] init];
        [_retryButton setImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_chat_retry_commit"] forState:UIControlStateNormal];
        [_retryButton addTarget:self action:@selector(retryButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _retryButton;
}

- (ICMessageTopView *)topView
{
    if (!_topView) {
        ICMessageTopView *topView = [[ICMessageTopView alloc] init];
        _topView                  = topView;
    }
    return _topView;
}

#pragma mark - Respond Method

- (void)retryButtonClick:(UIButton *)btn {
    if ([self.longPressDelegate respondsToSelector:@selector(reSendMessage:)]) {
        [self.longPressDelegate reSendMessage:self];
    }
}

- (void)setModelFrame:(ICMessageFrame *)modelFrame
{
    _modelFrame = modelFrame;
    
    ICMessageModel *messageModel = modelFrame.model;
    self.headImageView.frame     = modelFrame.headImageViewF;
    self.bubbleView.frame        = modelFrame.bubbleViewF;
   
    // 时间重用异常问题
    [self.topView removeFromSuperview];
    self.topView = nil;
    [self.contentView addSubview:self.topView];
    self.topView.frame           = modelFrame.topViewF;
    
    NSString *photoId = [ICMessageDatabase getPhotoIdWithEId:messageModel.message.from];
    if (messageModel.isSender) {    // 发送者
        self.activityView.frame  = modelFrame.activityF;
        self.retryButton.frame   = modelFrame.retryButtonF;
        [self.topView messageSendName:messageModel.message.senderName isSender:YES date:messageModel.message.date];
        switch (modelFrame.model.message.deliveryState) { // 发送状态
            case ICMessageDeliveryState_Delivering:
            {
                [self.activityView setHidden:NO];
                [self.retryButton setHidden:YES];
                [self.activityView startAnimating];
            }
                break;
            case ICMessageDeliveryState_Delivered:
            {
                [self.activityView stopAnimating];
                [self.activityView setHidden:YES];
                [self.retryButton setHidden:YES];
                
            }
                break;
            case ICMessageDeliveryState_Failure:
            {
                [self.activityView stopAnimating];
                [self.activityView setHidden:YES];
                [self.retryButton setHidden:NO];
            }
                break;
            default:
                break;
        }
        
        if ([modelFrame.model.message.type isEqualToString:TypeFile] ||
            [modelFrame.model.message.type isEqualToString:TypePicText] ||
            [modelFrame.model.message.type isEqualToString:TypeDrtNews] ||
            [modelFrame.model.message.type isEqualToString:TypeVideoConference])
        {
            self.bubbleView.image = [[UIImage imageNamedFromiComeSDKBundle:@"icon_chat_file_bubble_right"] stretchableImageWithLeftCapWidth:10 topCapHeight:35];
        } else if ([modelFrame.model.message.type isEqualToString:TypeRedPacket]) {
            self.bubbleView.image = [UIImage imageNamedFromiComeSDKBundle:@"icon_chat_redpacket_bubble_right"];
        } else {
            self.bubbleView.image = [[UIImage imageNamedFromiComeSDKBundle:@"icon_chat_bubble_right"]stretchableImageWithLeftCapWidth:10 topCapHeight:35];
        }
        
        NSString *eName = [ICMessageDatabase getUserNameWithEId:messageModel.message.from];
        NSString *URL = [ICTools getMinImageURL:(photoId)];
        [UIImage addAvatariamgeView:self.headImageView.imageView withUrlStr:URL witheId:messageModel.message.from withName:eName];
    } else {    // 接收者
        self.retryButton.hidden  = YES;
        if ([modelFrame.model.message.type isEqualToString:TypeRedPacket]) {
            self.bubbleView.image = [UIImage imageNamedFromiComeSDKBundle:@"icon_chat_redpacket_bubble_left"];
        } else {
            self.bubbleView.image    = [[UIImage imageNamedFromiComeSDKBundle:@"icon_chat_bubble_left"] stretchableImageWithLeftCapWidth:10 topCapHeight:35];
        }
        NSString *nName = [ICMessageDatabase nickNameWithEid:messageModel.message.from gId:messageModel.message.to];
        NSString *name  = [ICMessageDatabase getUserNameWithEId:messageModel.message.from];
        if (nName == nil) {
            messageModel.message.senderName = messageModel.message.senderName==nil?name:messageModel.message.senderName;
        } else {
            messageModel.message.senderName = messageModel.message.senderName==nil?nName:messageModel.message.senderName;
        }

        NSString *gId = messageModel.message.to;
        if ([gId hasPrefix:@"rbt_"]) { // 客服人员
            if ([gId isEqualToString:[NSString stringWithFormat:@"rbt_%@", [ICUser currentUser].eId]]) { //自己的rbt组
                [self.headImageView.imageView sd_setImageWithURL:[NSURL URLWithString:@""] placeholderImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_message_spirit_service"]];
                [self.topView messageSendName:@"平台客服" isSender:NO date:messageModel.message.date];
            } else {
                NSString *eName = [ICMessageDatabase getUserNameWithEId:messageModel.message.from];
                NSString *URL = [ICTools getMinImageURL:(photoId)];
                [UIImage addAvatariamgeView:self.headImageView.imageView withUrlStr:URL witheId:messageModel.message.from withName:eName];
                [self.topView messageSendName:messageModel.message.senderName isSender:NO date:messageModel.message.date];
            }
        } else {
            NSString *eName = [ICMessageDatabase getUserNameWithEId:messageModel.message.from];
            NSString *URL = [ICTools getMinImageURL:(photoId)];
            [UIImage addAvatariamgeView:self.headImageView.imageView withUrlStr:URL witheId:messageModel.message.from withName:eName];
            [self.topView messageSendName:messageModel.message.senderName isSender:NO date:messageModel.message.date];
        }
    }
}

- (void)headClicked:(UITapGestureRecognizer *)sender
{
    
    if (sender.numberOfTapsRequired == 1) {
        //单指单击
        if ([self.modelFrame.model.message.to isEqualToString:[NSString stringWithFormat:@"rbt_%@", [ICUser currentUser].eId]]) { //自己的rbt组
            if (!self.modelFrame.model.isSender) {
                return;// 关闭用户查看客服信息
            }
        }
        if ([self.longPressDelegate respondsToSelector:@selector(headImageClicked:)]) {
            [self.longPressDelegate headImageClicked:_modelFrame.model.message.from];
        }
        NSLog(@"单指单击");
    }else if(sender.numberOfTapsRequired == 2){
        //单指双击
        NSLog(@"单指双击");
        if(_modelFrame.model.message.from && _modelFrame.model.message.senderName){
            //\u2005
            NSString * name = [NSString stringWithFormat:@"%@\u2005",_modelFrame.model.message.senderName];
            
            NSDictionary * dict = @{_modelFrame.model.message.from:name};
            [self routerEventWithName:GXRouterEventsingleFingerTwo userInfo:dict];
        }
        
        
    }
    
}

-(void)longRecognizerClicked:(UILongPressGestureRecognizer *)longRecognizer
{
    if (longRecognizer.state == UIGestureRecognizerStateBegan) {
        if(_modelFrame.model.message.from && _modelFrame.model.message.senderName){
            //\u2005
            NSString * name = [NSString stringWithFormat:@"%@\u2005",_modelFrame.model.message.senderName];
            
            NSDictionary * dict = @{_modelFrame.model.message.from:name};
            [self routerEventWithName:GXRouterEventsingleFingerTwo userInfo:dict];
        }
        
    }
}

#pragma mark - longPress delegate

- (void)longPressRecognizer:(UILongPressGestureRecognizer *)recognizer
{
    if ([self.longPressDelegate respondsToSelector:@selector(longPress:)]) {
        [self.longPressDelegate longPress:recognizer];
    }
}




@end
